package com.github.cyf.common.validator;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import java.math.BigDecimal;

/**
 * @author chenyifan
 * @create 2024-09-30 15:02
 */
public class NumberScaleValidator implements ConstraintValidator<NumberScale, Number> {

    private int scale;

    public void initialize(NumberScale numberScaleAnnotation) {
        this.scale = numberScaleAnnotation.scale();
    }


    public boolean isValid(Number num, ConstraintValidatorContext constraintValidatorContext) {
        if (num == null) {
            return false;
        }
        BigDecimal bigNum;
        if (num instanceof BigDecimal) {
            bigNum = (BigDecimal) num;
        } else {
            bigNum = (new BigDecimal(num.toString()));
        }
        // 删除尾随零
        bigNum = bigNum.stripTrailingZeros();
        return this.scale >= bigNum.scale();
    }
}